<?php

class Controller{
	
	private $_dispatcher;
	public $params;
	public $autoRender = true;
	
	private $_view_vars;
	public $rendered = false;
	
	public function setDispatcher($dispatcher){
		$this->_dispatcher = $dispatcher;
	}
	public function getDispatcher(){
		return $this->_dispatcher;
	}
	public function __before() {
		
	}
	public function __after() {
		
	}
	public function error($code, $param) {
		global $ERROR;
		$this->set("code", $code);
		$this->set("title", $ERROR[$code][0]);
		$this->set("message", sprintf($ERROR[$code][1], $param));
		$this->render("error", "errors");
	}
	public function getMenu() {
		$user = Authentication::getUser();
		$menu = Xml::load(DIR_CONFIG . DIR_DELIMITER . "menu.xml");
		$menu = $this->_checkRoles($menu, $user["Role"]["code"]);
		return $menu;
	}
	private function _checkRoles($menu, $role){
		for($i=0; $i<count($menu->item); $i++){
			$item = $menu->item[$i];
			if(isset($item["role"]) && strtolower($item["role"])!=strtolower($role)){
				unset($menu->item[$i]);
			}elseif(!empty($item->menu)){
				$menu->item[$i]->menu->item = $this->_checkRoles($item->menu, $role);
			}
		}
		return $menu;
	}
	public function xhr(){
		return (int)$this->params->named["ajax"] ? true : false;
	}
	//------ VIEW METHODS ---------------------------------------------
	public function set($varname, $value) {
		$this->_view_vars[$varname] = $value;
	}
	public function parse($view) {
		
		$before = ob_get_contents();
		ob_clean();
		
		// include variables
		foreach($this->_view_vars as $name=>$value) {
			$$name = $value;
		}
		global $CONFIG;
		$CFG = $CONFIG["CORE"];
		
		$view = DIR_VIEWS . DIR_DELIMITER . $view . ".ctp";
		if(!file_exists($view)) {
			$this->error(1002, $view);
		}
		include $view;
		$return = ob_get_contents();
		
		ob_clean();
		echo $before;
		
		return $return;
	}
	public function parseElement($element, $pass=array()) {
		foreach($pass as $k=>$v){
			$this->set($k, $v);
		}
		return $this->parse("elements/$element");
	}
	public function layout() {
		global $CONFIG;
		$this->render($CONFIG["CORE"]["layout"], "layouts");
	}
	public function render($action=null, $controller=null) {
		$action = $action ? $action : $this->_dispatcher->getAction();
		$controller = $controller ? $controller : uncamelize(get_class($this));
		
		$view = $controller . DIR_DELIMITER . $action;
		echo $this->parse($view);

		$this->rendered = true;
	}
	public function setFlash($message, $status){
		$_SESSION["flash"] = array(
			"status" => $status,
			"message" => $message
		);
	}
	
	//------ MODEL METHODS ---------------------------------------------
	public function Model($model){
		$modelname = "{$model}Model";
		return new $modelname;
	}
}